﻿using System;
using System.Linq;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Daemon.Stages;
using JetBrains.ReSharper.Daemon.Xml.Highlightings;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Xml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using SPCAFContrib.ReSharper.Common;
using SPCAFContrib.ReSharper.Common.Attributes;
using SPCAFContrib.ReSharper.Common.Extensions;
using SPCAFContrib.ReSharper.Common.XmlAnalysis;
using SPCAFContrib.ReSharper.Consts;
using SPCAFContrib.ReSharper.Inspection.Xml.SPCAF;

[assembly: RegisterConfigurableSeverity(SPC055501Highlighting.CheckId,
  null,
  Consts.SPCAF_BEST_PRACTICES_GROUP,
  SPC055501Highlighting.CheckId + ": " + SPC055501Highlighting.Message,
  "The ListTemplate Type should be greater than 10000. This makes it easier to identify custom ListTemplates",
  Severity.WARNING,
  false, Internal = false)]

namespace SPCAFContrib.ReSharper.Inspection.Xml.SPCAF
{
    [Applicability(
        IDEProjectType.SP2010FarmSolution |
        IDEProjectType.SPSandbox |
        IDEProjectType.SP2013FarmSolution)]
    public class DefineListTemplateTypeGreaterThan10000 : XmlTagProblemAnalyzer
    {
        public override void Run(IXmlTag element, IHighlightingConsumer consumer)
        {
            if (element.GetProject().IsApplicableFor(this))
            {
                if (IsInvalid(element))
                {
                    SPC055501Highlighting errorHighlighting = new SPC055501Highlighting(element);
                    consumer.ConsumeHighlighting(element.Header.GetDocumentRange(), errorHighlighting);
                }
            }
        }

        public static bool IsInvalid(IXmlTag element)
        {
            bool result = false;

            if (element.Header.ContainerName == "ListTemplate" && element.AttributeExists("Type"))
            {
                var attr = element.GetAttribute("Type");
                int listtype = Convert.ToInt32(attr.UnquotedValue);
                result = listtype <= 10000;
            }

            return result;
        }
    }

    [ConfigurableSeverityHighlighting(CheckId, XmlLanguage.Name, OverlapResolve = OverlapResolveKind.NONE, ShowToolTipInStatusBar = true)]
    public class SPC055501Highlighting : XmlErrorHighlighting
    {
        public const string CheckId = "SPC055501";
        public const string Message = "Define Type of ListTemplate greater than 10000";

        public IXmlTag Element { get; private set; }

        public SPC055501Highlighting(IXmlTag element) :
            base(String.Format("{0}: {1}", CheckId, Message))
        {
            Element = element;
        }
    }
}
